<template>
  <div class="app-container">
    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <!-- 生产单元选择 -->
        <div class="filter-item">
          <span class="filter-label">生产单元：</span>
          <el-tree-select
            v-model="selectedUnit"
            :data="unitTreeData"
            :props="{ label: 'label', value: 'value', children: 'children' }"
            placeholder="请选择生产单元"
            style="width: 300px"
            @change="handleUnitChange"
            check-strictly
            node-key="value"
            :render-after-expand="false"
            :default-expanded-keys="[]"
            :default-checked-keys="[]"
            :show-checkbox="false"
            :check-on-click-node="true"
            :expand-on-click-node="false"
          />
        </div>

        <!-- 周期类别 -->
        <div class="filter-item">
          <span class="filter-label">周期类别：</span>
          <div class="time-granularity">
            <el-radio-group
              v-model="periodType"
              @change="handlePeriodTypeChange"
            >
              <el-radio-button label="day">日</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
              <el-radio-button label="year">年</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 生产周期 -->
        <div class="filter-item">
          <span class="filter-label">生产周期：</span>
          <el-date-picker
            v-model="selectedPeriod"
            :type="datePickerType"
            :format="dateFormat"
            :value-format="valueFormat"
            placeholder="选择日期"
            style="width: 200px"
          />
        </div>

        <!-- 搜索按钮 -->
        <el-button
          type="primary"
          icon="Search"
          @click="handleSearch"
          :loading="searchLoading"
        >
          搜索
        </el-button>
      </div>
    </div>

    <!-- 概览卡片区域 -->
    <div class="cards-section">
      <div class="cards-row">
        <!-- CO2总排放量 -->
        <div class="summary-card co2-total">
          <div class="card-icon">
            <SvgIcon iconClass="CO2" class="summary-svg" />
          </div>
          <div class="card-content">
            <div class="card-title">CO2排放总量</div>
            <div class="card-value">{{ totalCO2 }} t</div>
          </div>
        </div>

        <!-- 水 -->
        <div class="summary-card water">
          <div class="card-icon">
            <SvgIcon iconClass="water" class="summary-svg" />
          </div>
          <div class="card-content">
            <div class="card-title">水</div>
            <div class="card-detail">总量 {{ waterTotal }} t</div>
            <div class="card-detail">CO2 {{ waterCO2 }} t</div>
          </div>
        </div>

        <!-- 电 -->
        <div class="summary-card electricity">
          <div class="card-icon">
            <SvgIcon iconClass="electricity" class="summary-svg" />
          </div>
          <div class="card-content">
            <div class="card-title">电</div>
            <div class="card-detail">
              总量 {{ electricityTotal }} kg-co2/kW.h
            </div>
            <div class="card-detail">CO2 {{ electricityCO2 }} t</div>
          </div>
        </div>

        <!-- 气 -->
        <div class="summary-card gas">
          <div class="card-icon">
            <SvgIcon iconClass="gas" class="summary-svg" />
          </div>
          <div class="card-content">
            <div class="card-title">气</div>
            <div class="card-detail">总量 {{ gasTotal }} m³</div>
            <div class="card-detail">CO2 {{ gasCO2 }} t</div>
          </div>
    </div>
    
        <!-- 热 -->
        <div class="summary-card heat">
          <div class="card-icon">
            <SvgIcon iconClass="heat" class="summary-svg" />
          </div>
        <div class="card-content">
            <div class="card-title">热</div>
            <div class="card-detail">总量 {{ heatTotal }} GJ</div>
            <div class="card-detail">CO2 {{ heatCO2 }} t</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 柱状图详情区域 -->
    <div class="chart-section">
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>{{ chartTitle }}</h3>
        </div>
        <div class="chart-container">
          <v-chart :option="chartOption" class="co2-chart" v-loading="chartLoading" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart from "vue-echarts";
// 移除 Element Plus 图标导入，使用本地 SVG 图标
import { listEnergyUnit } from "@/api/deviceManage/energyUnit";
import { getHourlyStatisticsCarbon } from "@/api/stat/home";
import { ElMessage } from "element-plus";
import SvgIcon from "@/components/SvgIcon/index.vue";

// 注册ECharts组件
use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// 基础数据
const selectedUnit = ref("");
const periodType = ref("month");
const selectedPeriod = ref("");
const searchLoading = ref(false);
const chartLoading = ref(false);
const themeColor = "#16A5B7";
const chartOption = ref({
  title: {
    text: "",
    left: "center",
    textStyle: {
      fontSize: 16,
      fontWeight: "bold",
      color: "#2c3e50",
    },
  },
  tooltip: {
    show: true,
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
  },
  legend: {
    data: [],
    top: 10,
    right: 20,
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    top: "15%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: [],
    axisLabel: {
      rotate: 45,
    },
  },
  yAxis: {
    type: "value",
    name: "CO2排放量 (Kg)",
    nameTextStyle: {
      color: "#666",
    },
  },
  series: [],
});

// 生产单元树形数据（从接口获取）
const unitTreeData = ref([]);
const unitLoading = ref(false);

// 概览数据
const totalCO2 = ref(0.02);
const waterTotal = ref(150.5);
const waterCO2 = ref(0.01);
const electricityTotal = ref(72.8);
const electricityCO2 = ref(0.02);
const gasTotal = ref(89.2);
const gasCO2 = ref(0.015);
const heatTotal = ref(45.6);
const heatCO2 = ref(0.008);

// 图表数据
const chartData = ref([]);

// 计算属性
const datePickerType = computed(() => {
  switch (periodType.value) {
    case "day":
      return "date";
    case "month":
      return "month";
    case "year":
      return "year";
    default:
      return "month";
  }
});

const dateFormat = computed(() => {
  switch (periodType.value) {
    case "day":
      return "YYYY-MM-DD";
    case "month":
      return "YYYY-MM";
    case "year":
      return "YYYY";
    default:
      return "YYYY-MM";
  }
});

const valueFormat = computed(() => {
  switch (periodType.value) {
    case "day":
      return "YYYY-MM-DD";
    case "month":
      return "YYYY-MM";
    case "year":
      return "YYYY";
    default:
      return "YYYY-MM";
  }
});

// 获取选中节点的标签
const getSelectedUnitLabel = () => {
  const findLabel = (nodes, value) => {
    for (const node of nodes) {
      // 确保类型匹配比较
      if (node.value == value) {
        return node.label;
      }
      if (node.children) {
        const found = findLabel(node.children, value);
        if (found) return found;
      }
    }
    return null;
  };
  return findLabel(unitTreeData.value, selectedUnit.value) || "生产单元";
};

const chartTitle = computed(() => {
  const unitName = getSelectedUnitLabel();
  const periodText = selectedPeriod.value || "2025年10月";
  return `${unitName}-CO2排放量详情 (${periodText})`;
});

// 事件处理
function handleUnitChange(value) {
  console.log("生产单元变更:", value);
  console.log("当前选中的值:", selectedUnit.value);
  
  // 查找选中的节点信息
  const findNode = (nodes, val) => {
    for (const node of nodes) {
      if (node.value === val) {
        return node;
      }
      if (node.children) {
        const found = findNode(node.children, val);
        if (found) return found;
      }
    }
    return null;
  };
  
  const selectedNode = findNode(unitTreeData.value, value);
  console.log("选中的节点信息:", selectedNode);
}

function handlePeriodTypeChange() {
  console.log("周期类别变更:", periodType.value);
  // 清空选中的日期
  selectedPeriod.value = "";
}

async function handleSearch() {
  if (!selectedUnit.value || !selectedPeriod.value) {
    ElMessage.warning("请选择生产单元和生产周期");
    return;
  }

  searchLoading.value = true;
  chartLoading.value = true;

  try {
    // 调用真实的接口
    const params = {
      groupId: selectedUnit.value,
      statTime: selectedPeriod.value
    };
    
    console.log("调用接口参数:", params);
    const response = await getHourlyStatisticsCarbon(params);
    console.log("接口返回数据:", response);

    // 兼容不同的返回结构：{code,msg,data} 或 直接 data
    const payload = (response && response.data && (response.data.data ?? response.data)) || response || {};
    console.log("解析后的数据:", payload);

    if (payload && (payload.dayData || payload.beforeDayData)) {
      // 处理接口返回的数据
      processApiData(payload);
    } else {
      // 如果没有数据，使用模拟数据
      loadChartData();
    }
  } catch (error) {
    console.error("获取碳排放数据失败:", error);
    ElMessage.error("获取数据失败，请重试");
    // 出错时使用模拟数据
    loadChartData();
  } finally {
    searchLoading.value = false;
    chartLoading.value = false;
  }
}

// 处理接口返回的数据
function processApiData(data) {
  console.log("处理接口数据:", data);
  
  // 处理totalData - 各个能源类型的碳排放总量
  if (data.totalData && Array.isArray(data.totalData)) {
    console.log("处理totalData:", data.totalData);
    
    // 初始化各能源类型的CO2排放量
    let waterCO2Value = 0;
    let electricityCO2Value = 0;
    let gasCO2Value = 0;
    let heatCO2Value = 0;
    let totalCO2Value = 0;
    
    // 根据energyType分类处理数据
    data.totalData.forEach(item => {
      const co2Value = item.carbonEmissions || 0; // 使用carbonEmissions字段
      const sumValue = item.sum_value || 0; // 使用sum_value字段
      
      switch (item.energyType) {
        case 10: // 水
          waterCO2Value = co2Value;
          waterTotal.value = parseFloat(sumValue.toFixed(2));
          break;
        case 20: // 电
          electricityCO2Value = co2Value;
          electricityTotal.value = parseFloat(sumValue.toFixed(2));
          break;
        case 30: // 气
          gasCO2Value = co2Value;
          gasTotal.value = parseFloat(sumValue.toFixed(2));
          break;
        case 40: // 热
          heatCO2Value = co2Value;
          heatTotal.value = parseFloat(sumValue.toFixed(2));
          break;
      }
      
      totalCO2Value += co2Value;
    });
    
    // 更新CO2排放量（转换为吨）
    waterCO2.value = parseFloat(waterCO2Value.toFixed(3));
    electricityCO2.value = parseFloat(electricityCO2Value.toFixed(3));
    gasCO2.value = parseFloat(gasCO2Value.toFixed(3));
    heatCO2.value = parseFloat(heatCO2Value.toFixed(3));
    totalCO2.value = parseFloat(totalCO2Value.toFixed(3));
    
    console.log("更新后的CO2排放量:", {
      waterCO2: waterCO2.value,
      electricityCO2: electricityCO2.value,
      gasCO2: gasCO2.value,
      heatCO2: heatCO2.value,
      totalCO2: totalCO2.value
    });
  }
  
  // 获取当前期和上期数据
  const dayData = Array.isArray(data.dayData) ? data.dayData : [];
  const beforeDayData = Array.isArray(data.beforeDayData) ? data.beforeDayData : [];

  if (dayData && dayData.length > 0) {
    
    // 处理图表数据
    const chartDataList = [];
    
    dayData.forEach((item, index) => {
      // 提取日期（从hourName中提取）
      let dayLabel = '';
      if (item.hourName && item.hourName.includes('-')) {
        const dateParts = item.hourName.split('-');
        if (dateParts.length >= 3) {
          dayLabel = dateParts[2] + '日';
        } else {
          dayLabel = item.hourName;
        }
      } else {
        dayLabel = item.hourName || '';
      }
      
      // 本期数据：使用dayData中的sum_value
      const currentValue = parseFloat((item.sum_value || 0).toFixed(2));
      
      // 上期数据：使用beforeDayData中对应索引的sum_value
      let previousValue = null; // 使用null表示没有数据
      if (beforeDayData && beforeDayData[index] && beforeDayData[index].sum_value !== undefined) {
        previousValue = parseFloat((beforeDayData[index].sum_value || 0).toFixed(2));
      }
      
      chartDataList.push({
        day: dayLabel,
        current: currentValue,
        previous: previousValue
      });
    });
    
    chartData.value = chartDataList;
    updateChart();
    
    console.log("处理后的图表数据:", chartData.value);
    console.log("总CO2排放量:", totalCO2.value, "t");
  } else {
    // 如果没有统计数据，使用模拟数据
    loadChartData();
  }
}

// 将后端树结构转换为 el-tree-select 需要的 {label,value,children}
function transformUnitTree(nodes) {
  if (!Array.isArray(nodes)) return [];
  return nodes.map((n) => ({
    label: n.label || n.name || `节点${n.id}`, // 确保有标签显示
    value: n.id,
    disabled: false, // 所有节点都设为可选
    children: n.children ? transformUnitTree(n.children) : [],
  }));
}

async function fetchUnitTree() {
  try {
    unitLoading.value = true;
    const { data } = await listEnergyUnit();
    console.log("原始数据:", data);
    unitTreeData.value = transformUnitTree(data || []);
    console.log("转换后数据:", unitTreeData.value);
    console.log("树形选择器数据:", JSON.stringify(unitTreeData.value, null, 2));
    
    // 默认选中第一个节点
    if (!selectedUnit.value) {
      const findFirstNode = (nodes) => {
        for (const node of nodes) {
          // 直接返回第一个节点，不管是否有子节点
          return node.value;
        }
        return null;
      };
      const firstNode = findFirstNode(unitTreeData.value);
      if (firstNode) {
        selectedUnit.value = firstNode; // 保持数字类型，不转换为字符串
        console.log("默认选中节点:", selectedUnit.value);
        console.log("选中节点类型:", typeof selectedUnit.value);
      }
    }
  } catch (e) {
    console.error("获取用能单元树失败", e);
  } finally {
    unitLoading.value = false;
  }
}

function loadChartData() {
  // 生成模拟数据
  const data = [];
  const daysInMonth = 31;

  for (let day = 1; day <= daysInMonth; day++) {
    // 本期值 - 大部分接近0，少数几天有值
    let currentValue = 0;
    if ([5, 6, 7].includes(day)) {
      currentValue = Math.random() * 20 + 5;
    }

    // 上期值 - 某些天有高峰
    let previousValue = Math.random() * 30;
    if ([9, 10, 18, 20, 26].includes(day)) {
      previousValue = Math.random() * 40 + 80;
    }

    data.push({
      day: `${day}日`,
      current: parseFloat(currentValue.toFixed(1)),
      previous: parseFloat(previousValue.toFixed(1)),
    });
  }

  chartData.value = data;
  updateChart();
}

function initChart() {
  // 初始化图表配置
  chartOption.value.title.text = chartTitle.value;
}

function updateChart() {
  if (!chartData.value.length) return;

  const days = chartData.value.map((item) => item.day);
  const currentValues = chartData.value.map((item) => item.current);
  const previousValues = chartData.value.map((item) => item.previous);

  // 检查是否有上期数据
  const hasPreviousData = previousValues.some(value => value !== null);

  const series = [
    {
      name: "本期值",
      type: "bar",
      data: currentValues,
      itemStyle: {
        color: "#4fdaca",
      },
    }
  ];

  // 只有当有上期数据时才添加上期系列
  if (hasPreviousData) {
    series.push({
      name: "上期值",
      type: "bar",
      data: previousValues,
      itemStyle: {
        color: "#d3d3d3",
      },
    });
  }

  // 动态设置图例数据
  const legendData = hasPreviousData ? ["本期值", "上期值"] : ["本期值"];

  // 更新图表配置
  chartOption.value = {
    title: {
      text: chartTitle.value,
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2c3e50",
      },
    },
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {
      data: legendData,
      top: 10,
      right: 20,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: days,
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: "value",
      name: "CO2排放量 (Kg)",
      nameTextStyle: {
        color: "#666",
      },
    },
    series: series,
  };
}

// 页面初始化
onMounted(async () => {
  // 默认日期
  selectedPeriod.value = "2025-10";
  // 加载用能单元树
  await fetchUnitTree();
  // 初始化图表
  nextTick(() => {
    initChart();
    // 如果有选中的单元和日期，自动调用接口
    if (selectedUnit.value && selectedPeriod.value) {
      handleSearch();
    } else {
      // 否则使用模拟数据
      loadChartData();
    }
  });
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f1f2f5;
  height: 100%;
  overflow-y: auto;
}

// 筛选条件区域
.filter-section {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .filter-row {
    display: flex;
    align-items: center;
    gap: 24px;
    flex-wrap: wrap;

    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
        white-space: nowrap;
      }
    }
  }
}

// 概览卡片区域
.cards-section {
  margin-bottom: 20px;
  
  .cards-row {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;

    .summary-card {
      background: #ffffff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      gap: 16px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      .card-icon {
        flex-shrink: 0;

        .summary-svg {
          width: 48px;
          height: 48px;
          object-fit: contain;
          color: #16a5b7 !important; // 统一主题色
        }
      }

      .card-content {
        flex: 1;

        .card-title {
          font-size: 14px;
          color: #606266;
          font-weight: 500;
          margin-bottom: 8px;
        }

        .card-value {
    font-size: 24px;
    font-weight: 600;
          color: #2c3e50;
        }

        .card-detail {
          font-size: 12px;
          color: #909399;
          margin-bottom: 4px;
          line-height: 1.4;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }

      // 覆盖 SvgIcon 默认色
      :deep(.svg-icon) {
        color: #16a5b7 !important;
      }
    }
  }
}

// 图表区域
.chart-section {
  height: 500px;
  .chart-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .chart-header {
      padding: 20px 20px 0 20px;
      border-bottom: 1px solid #e4e7ed;

      h3 {
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;
        margin: 0 0 16px 0;
      }
    }

    .chart-container {
      padding: 20px;

      .co2-chart {
        width: 100%;
        height: 500px;
        background: #ffffff;
        border-radius: 8px;
      }
    }
  }
}

// 周期类别按钮组样式 - 参考负荷分析页面
.time-granularity {
  :deep(.el-radio-group) {
    display: flex;
    gap: 8px;

    .el-radio-button {
      margin-right: 0;
    }

    .el-radio-button__inner {
      border-radius: 6px;
      border: 1px solid #dcdfe6;
      background: #ffffff;
      color: #606266;
      font-weight: 500;
      padding: 8px 16px;

      &:hover {
        color: #16a5b7;
        border-color: #16a5b7;
      }
    }

    .el-radio-button__original-radio:checked + .el-radio-button__inner {
      background: linear-gradient(135deg, #16a5b7 0%, #138a9a 100%);
      border-color: #16a5b7;
      color: #ffffff;
      box-shadow: 0 2px 4px rgba(22, 165, 183, 0.3);
    }
  }
}

// 日期选择器样式
:deep(.el-date-editor) {
  .el-input__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #16a5b7;
    }

    &.is-focus {
      border-color: #16a5b7;
      box-shadow: 0 0 0 2px rgba(22, 165, 183, 0.2);
    }
  }
}

// 树形选择器样式
:deep(.el-tree-select) {
  .el-select__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #16a5b7;
    }

    &.is-focused {
      border-color: #16a5b7;
      box-shadow: 0 0 0 2px rgba(22, 165, 183, 0.2);
    }
  }
}

// 按钮样式
:deep(.el-button) {
  border-radius: 6px;

  &.el-button--primary {
    background: linear-gradient(135deg, #16a5b7 0%, #138a9a 100%);
    border: none;
    color: #ffffff;

    &:hover {
      background: linear-gradient(135deg, #138a9a 0%, #0f6b7a 100%);
      color: #ffffff;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .cards-section .cards-row {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .cards-section .cards-row {
    grid-template-columns: repeat(2, 1fr);
  }

  .filter-section .filter-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .filter-item {
      width: 100%;
      justify-content: space-between;
    }
  }
}

@media (max-width: 480px) {
  .cards-section .cards-row {
    grid-template-columns: 1fr;
  }
}
</style>
